package org.lex.event;

import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.EventListenerList;

public class ChangeSupport {
	private EventListenerList listenerList = new EventListenerList();

	public void add(ChangeListener l) {
		listenerList.add(ChangeListener.class, l);
	}

	public int getListenerCount() {
		return listenerList.getListenerCount();
	}

	public Object[] getListenerList() {
		return listenerList.getListenerList();
	}

	public void remove(ChangeListener l) {
		listenerList.remove(ChangeListener.class, l);
	}

	protected void fireStateChanged(ChangeEvent e) {
		// Notify all listeners that have registered interest for
		// notification on this event type. The event instance
		// is lazily created using the parameters passed into
		// the fire method.

		// Guaranteed to return a non-null array
		Object[] listeners = listenerList.getListenerList();
		// Process the listeners last to first, notifying
		// those that are interested in this event
		for (int i = listeners.length - 2; i >= 0; i -= 2) {
			if (listeners[i] == ChangeListener.class) {
				// Lazily create the event:
				((ChangeListener) listeners[i + 1]).stateChanged(e);
			}
		}
	}

	protected void fireInEDT(ChangeEvent e) {
		SwingUtilities.invokeLater(buildFire(e));
	}

	protected Runnable buildFire(final ChangeEvent e) {
		return new Runnable() {
			public void run() {
				fireStateChanged(e);
			}
		};
	}
}
